from flask import Flask, render_template, redirect, url_for, request, flash, send_file, session
import os
import sys
sys.path.append('../后端')
from collections import defaultdict
try:
    from mode12菜单版 import (
        add_customer, view_all_customers, update_customer, delete_customer, export_customers_to_csv,
        add_bankcard, view_all_bankcards, delete_bankcard, report_loss, unreport_loss, change_card_password, check_loss_status, export_bankcards_to_csv,
        add_deposit, view_all_deposits, update_deposit, delete_deposit, export_deposits_to_csv,
        add_transaction, view_all_transactions, delete_transaction, export_transactions_to_csv,
        verify_customer_login, get_customer_name_by_cardID, update_bankcard, query_userinfo, query_cardinfo, query_deposit
    )
except ImportError as e:
    print(f"导入错误: {e}")
    def add_customer(*args, **kwargs):
        pass
    def view_all_customers(*args, **kwargs):
        return []
    def update_customer(*args, **kwargs):
        pass
    def delete_customer(*args, **kwargs):
        pass
    def export_customers_to_csv(*args, **kwargs):
        pass
    def add_bankcard(*args, **kwargs):
        pass
    def view_all_bankcards(*args, **kwargs):
        return []
    def delete_bankcard(*args, **kwargs):
        pass
    def report_loss(*args, **kwargs):
        pass
    def unreport_loss(*args, **kwargs):
        pass
    def change_card_password(*args, **kwargs):
        pass
    def check_loss_status(*args, **kwargs):
        return None
    def export_bankcards_to_csv(*args, **kwargs):
        pass
    def add_deposit(*args, **kwargs):
        pass
    def view_all_deposits(*args, **kwargs):
        return []
    def update_deposit(*args, **kwargs):
        pass
    def delete_deposit(*args, **kwargs):
        pass
    def export_deposits_to_csv(*args, **kwargs):
        pass
    def add_transaction(*args, **kwargs):
        pass
    def view_all_transactions(*args, **kwargs):
        return []
    def delete_transaction(*args, **kwargs):
        pass
    def export_transactions_to_csv(*args, **kwargs):
        pass
    def verify_customer_login(*args, **kwargs):
        return False
    def get_customer_name_by_cardID(*args, **kwargs):
        return "未知用户"
    def update_bankcard(*args, **kwargs):
        pass
    def query_userinfo(*args, **kwargs):
        return []
    def query_cardinfo(*args, **kwargs):
        return []
    def query_deposit(*args, **kwargs):
        return []

app = Flask(__name__)
app.secret_key = 'bank_secret_key'

@app.route('/', methods=['GET', 'POST'])
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        user_type = request.form.get('user_type')
        username = request.form.get('username')
        password = request.form.get('password')
        
        if user_type == 'admin':
            if username == '666666' and password == '123456':
                session['user_type'] = 'admin'
                session['username'] = username
                flash('管理员登录成功！', 'success')
                return redirect(url_for('admin_menu'))
            else:
                flash('管理员账号或密码错误！', 'error')
                return redirect(url_for('login'))
        
        elif user_type == 'customer':
            if verify_customer_login(username, password):
                # 查询客户名
                customer_name = get_customer_name_by_cardID(username)
                session['user_type'] = 'customer'
                session['username'] = username
                session['cardID'] = username  # 假设登录用卡号
                session['cardmima'] = password
                session['customer_name'] = customer_name
                flash('登录成功！', 'success')
                return redirect(url_for('customer_menu'))
            else:
                flash('客户账号或密码错误！', 'error')
                return redirect(url_for('login'))

    return render_template('login.html')

@app.route('/admin_menu')
def admin_menu():
    return render_template('admin_menu.html')

@app.route('/customer_menu')
def customer_menu():
    if session.get('user_type') != 'customer':
        return redirect(url_for('login'))
    return render_template('customer_menu.html')

@app.route('/logout')
def logout():
    session.clear() # 清除所有 session 数据
    flash('您已成功退出登录。', 'success')
    return redirect(url_for('login'))

@app.route('/customer_manage')
def customer_manage():
    return render_template('customer_manage.html')

@app.route('/customer_add', methods=['GET', 'POST'])
def customer_add():
    if request.method == 'POST':
        customerName = request.form.get('customerName')
        PID = request.form.get('PID')
        telephone = request.form.get('telephone')
        address = request.form.get('address')
        try:
            add_customer(customerName, PID, telephone, address)
            flash(f'成功添加客户：{customerName}', 'success')
            return redirect(url_for('customer_add'))
        except Exception as e:
            flash(f'添加客户失败：{e}', 'error')
    return render_template('customer_add.html')

@app.route('/customer_list')
def customer_list():
    try:
        customers = view_all_customers()
        print('customers from db:', customers)  # 调试用
    except Exception as e:
        flash(f'查询失败：{e}', 'error')
        customers = []
    return render_template('customer_list.html', customers=customers)

@app.route('/customer_update', methods=['GET', 'POST'])
def customer_update():
    if request.method == 'POST':
        customerID = request.form.get('customerID')
        customerName = request.form.get('customerName')
        telephone = request.form.get('telephone')
        address = request.form.get('address')
        try:
            update_customer(customerID, customerName or None, telephone or None, address or None)
            flash(f'成功更新客户：{customerID}', 'success')
            return redirect(url_for('customer_update'))
        except Exception as e:
            flash(f'更新客户失败：{e}', 'error')
    return render_template('customer_update.html')

@app.route('/customer_delete', methods=['GET', 'POST'])
def customer_delete():
    if request.method == 'POST':
        customerID = request.form.get('customerID')
        try:
            delete_customer(customerID)
            flash(f'成功删除客户：{customerID}', 'success')
            return redirect(url_for('customer_delete'))
        except Exception as e:
            flash(f'删除客户失败：{e}', 'error')
    return render_template('customer_delete.html')

@app.route('/customer_export')
def customer_export():
    try:
        export_customers_to_csv()
        # 假设导出到固定路径
        file_path = r"D:/UNIVERSITY WORK/大二下/DBkeshe/bank_system/客户管理.csv"
        return send_file(file_path, as_attachment=True)
    except Exception as e:
        flash(f'导出失败：{e}', 'error')
        return redirect(url_for('customer_manage'))

# ------------------ 银行卡管理 ------------------
@app.route('/bankcard_manage')
def bankcard_manage():
    return render_template('bankcard_manage.html')

@app.route('/bankcard_add', methods=['GET', 'POST'])
def bankcard_add():
    if request.method == 'POST':
        curID = request.form.get('curID')
        savingID = request.form.get('savingID')
        openMoney = request.form.get('openMoney')
        customerID = request.form.get('customerID')
        try:
            add_bankcard(curID, savingID, openMoney, customerID)
            flash(f'成功添加银行卡', 'success')
            return redirect(url_for('bankcard_add'))
        except Exception as e:
            flash(f'添加银行卡失败：{e}', 'error')
    # 新增：获取所有存款类型编号和名称
    deposits = view_all_deposits()
    saving_options = [{'id': d['savingID'], 'name': d.get('savingName', d['savingID'])} for d in deposits]
    return render_template('bankcard_add.html', saving_options=saving_options)

@app.route('/bankcard_list')
def bankcard_list():
    if 'user_type' not in session or session['user_type'] != 'admin':
        flash('请以管理员身份登录后访问。', 'error')
        return redirect(url_for('login'))
    try:
        bankcards = view_all_bankcards()
    except Exception as e:
        flash(f'查询失败：{e}', 'error')
        bankcards = []
    return render_template('bankcard_list.html', bankcards=bankcards)

@app.route('/bankcard_delete', methods=['GET', 'POST'])
def bankcard_delete():
    if request.method == 'POST':
        cardID = request.form.get('cardID')
        try:
            delete_bankcard(cardID)
            flash(f'成功删除银行卡：{cardID}', 'success')
            return redirect(url_for('bankcard_delete'))
        except Exception as e:
            flash(f'删除银行卡失败：{e}', 'error')
    return render_template('bankcard_delete.html')

@app.route('/bankcard_export')
def bankcard_export():
    try:
        export_bankcards_to_csv()
        # 假设导出到固定路径
        file_path = r"D:/UNIVERSITY WORK/大二下/DBkeshe/bank_system/银行卡管理.csv"
        return send_file(file_path, as_attachment=True)
    except Exception as e:
        flash(f'导出失败：{e}', 'error')
        return redirect(url_for('bankcard_manage'))

@app.route('/bankcard_update', methods=['GET', 'POST'])
def bankcard_update():
    cardinfo = None
    # 获取所有存款类型编号和名称
    deposits = view_all_deposits()
    saving_options = [{'id': d['savingID'], 'name': d.get('savingName', d['savingID'])} for d in deposits]
    
    if request.method == 'POST':
        from mode12菜单版 import update_bankcard
        action = request.form.get('action')
        cardID = request.form.get('cardID')
        if action == 'search':
            # 查询卡信息
            import pymysql
            conn = pymysql.connect(host="localhost", port=3306, user="root", password="69296616", database="dbkeshe", cursorclass=pymysql.cursors.DictCursor)
            cursor = conn.cursor()
            cursor.execute('SELECT * FROM cardinfo WHERE cardID=%s', (cardID,))
            cardinfo = cursor.fetchone()
            conn.close()
            if not cardinfo:
                flash('未找到该银行卡号', 'error')
        elif action == 'update':
            curID = request.form.get('curID')
            savingID = request.form.get('savingID')
            cardmima = request.form.get('cardmima')
            IsReportLoss = request.form.get('IsReportLoss')
            try:
                update_bankcard(cardID, curID, savingID, cardmima, IsReportLoss)
                flash('银行卡信息修改成功', 'success')
            except Exception as e:
                flash(f'修改失败：{e}', 'error')
            # 查询最新信息回显
            import pymysql
            conn = pymysql.connect(host="localhost", port=3306, user="root", password="69296616", database="dbkeshe", cursorclass=pymysql.cursors.DictCursor)
            cursor = conn.cursor()
            cursor.execute('SELECT * FROM cardinfo WHERE cardID=%s', (cardID,))
            cardinfo = cursor.fetchone()
            conn.close()
    return render_template('bankcard_update.html', cardinfo=cardinfo, saving_options=saving_options)

@app.route('/deposit_manage')
def deposit_manage():
    return render_template('deposit_manage.html')

@app.route('/deposit_add', methods=['GET', 'POST'])
def deposit_add():
    if request.method == 'POST':
        savingName = request.form.get('savingName')
        descrip = request.form.get('descrip')
        cardID = request.form.get('cardID')
        try:
            add_deposit(savingName, descrip, cardID)
            flash(f'成功添加存款记录', 'success')
            return redirect(url_for('deposit_add'))
        except Exception as e:
            flash(f'添加存款失败：{e}', 'error')
    return render_template('deposit_add.html')

@app.route('/deposit_list')
def deposit_list():
    try:
        deposits = view_all_deposits()
    except Exception as e:
        flash(f'查询失败：{e}', 'error')
        deposits = []
    return render_template('deposit_list.html', deposits=deposits)

@app.route('/deposit_update', methods=['GET', 'POST'])
def deposit_update():
    if request.method == 'POST':
        savingID = request.form.get('savingID')
        savingName = request.form.get('savingName')
        descrip = request.form.get('descrip')
        cardID = request.form.get('cardID')
        try:
            update_deposit(savingID, savingName or None, descrip or None, cardID or None)
            flash(f'成功更新存款记录：{savingID}', 'success')
            return redirect(url_for('deposit_update'))
        except Exception as e:
            flash(f'更新存款失败：{e}', 'error')
    return render_template('deposit_update.html')

@app.route('/deposit_delete', methods=['GET', 'POST'])
def deposit_delete():
    if request.method == 'POST':
        savingID = request.form.get('savingID')
        try:
            delete_deposit(savingID)
            flash(f'成功删除存款记录：{savingID}', 'success')
            return redirect(url_for('deposit_delete'))
        except Exception as e:
            flash(f'删除存款失败：{e}', 'error')
    return render_template('deposit_delete.html')

@app.route('/deposit_export')
def deposit_export():
    try:
        export_deposits_to_csv()
        file_path = r"D:/UNIVERSITY WORK/大二下/DBkeshe/bank_system/存款管理.csv"
        return send_file(file_path, as_attachment=True)
    except Exception as e:
        flash(f'导出失败：{e}', 'error')
        return redirect(url_for('deposit_manage'))

@app.route('/transaction_manage')
def transaction_manage():
    return render_template('transaction_manage.html')

@app.route('/transaction_list')
def transaction_list():
    try:
        transactions = view_all_transactions()
    except Exception as e:
        flash(f'查询失败：{e}', 'error')
        transactions = []
    return render_template('transaction_list.html', transactions=transactions)

@app.route('/transaction_delete', methods=['GET', 'POST'])
def transaction_delete():
    if request.method == 'POST':
        tradeID = request.form.get('tradeID')
        try:
            delete_transaction(tradeID)
            flash(f'成功删除交易记录：{tradeID}', 'success')
            return redirect(url_for('transaction_delete'))
        except Exception as e:
            flash(f'删除交易失败：{e}', 'error')
    return render_template('transaction_delete.html')

@app.route('/transaction_export')
def transaction_export():
    try:
        export_transactions_to_csv()
        file_path = r"D:/UNIVERSITY WORK/大二下/DBkeshe/bank_system/交易管理.csv"
        return send_file(file_path, as_attachment=True)
    except Exception as e:
        flash(f'导出失败：{e}', 'error')
        return redirect(url_for('transaction_manage'))

@app.route('/customer_deposit', methods=['GET', 'POST'])
def customer_deposit():
    if request.method == 'POST':
        cardID = request.form.get('cardID')
        cardmima = request.form.get('cardmima')
        amount = request.form.get('amount')
        try:
            from mode12菜单版 import customer_deposit_web as deposit_func
            result = deposit_func(cardID, cardmima, amount)
            if isinstance(result, str) and (result.startswith('存款成功') or result.replace('.', '', 1).isdigit()):
                flash(result, 'success')
            else:
                flash(f'存款失败：{result}', 'error')
            return redirect(url_for('customer_deposit'))
        except Exception as e:
            flash(f'存款失败：{e}', 'error')
    return render_template('customer_deposit.html')

@app.route('/customer_withdraw', methods=['GET', 'POST'])
def customer_withdraw():
    if request.method == 'POST':
        cardID = request.form.get('cardID')
        cardmima = request.form.get('cardmima')
        amount = request.form.get('amount')
        try:
            from mode12菜单版 import customer_withdraw_web as withdraw_func
            result = withdraw_func(cardID, cardmima, amount)
            if isinstance(result, str) and (result.startswith('取款成功') or result.replace('.', '', 1).isdigit()):
                flash(result, 'success')
            else:
                flash(f'取款失败：{result}', 'error')
            return redirect(url_for('customer_withdraw'))
        except Exception as e:
            flash(f'取款失败：{e}', 'error')
    return render_template('customer_withdraw.html')

@app.route('/customer_transfer', methods=['GET', 'POST'])
def customer_transfer():
    if request.method == 'POST':
        from_cardID = request.form.get('from_cardID')
        from_cardmima = request.form.get('from_cardmima')
        to_cardID = request.form.get('to_cardID')
        amount = request.form.get('amount')
        try:
            from mode12菜单版 import customer_transfer_web as transfer_func
            result = transfer_func(from_cardID, from_cardmima, to_cardID, amount)
            if isinstance(result, str) and (result.startswith('转账成功') or result.replace('.', '', 1).isdigit()):
                flash(result, 'success')
            else:
                flash(f'转账失败：{result}', 'error')
            return redirect(url_for('customer_transfer'))
        except Exception as e:
            flash(f'转账失败：{e}', 'error')
    return render_template('customer_transfer.html')

@app.route('/customer/balance', methods=['GET', 'POST'])
def customer_balance():
    if session.get('user_type') != 'customer':
        return redirect(url_for('login'))
    balance = None
    if request.method == 'POST':
        cardID = session.get('cardID')
        cardmima = request.form.get('cardmima')
        try:
            from mode12菜单版 import customer_check_balance_web as check_func
            balance = check_func(cardID, cardmima)
            if isinstance(balance, str) and not balance.replace('.', '', 1).isdigit():
                flash(f'查询失败：{balance}', 'error')
            else:
                flash(f'当前余额：{balance}', 'success')
        except Exception as e:
            flash(f'查询失败：{e}', 'error')
    return render_template('customer_balance.html', balance=balance)

@app.route('/customer_report_loss', methods=['GET', 'POST'])
def customer_report_loss():
    if request.method == 'POST':
        cardID = request.form.get('cardID')
        cardmima = request.form.get('cardmima')
        try:
            from mode12菜单版 import customer_report_loss_web as report_func
            result = report_func(cardID, cardmima)
            if result == '挂失成功':
                flash(result, 'success')
            else:
                flash(f'挂失失败：{result}', 'error')
            return redirect(url_for('customer_report_loss'))
        except Exception as e:
            flash(f'挂失失败：{e}', 'error')
    return render_template('customer_report_loss.html')

@app.route('/customer_unreport_loss', methods=['GET', 'POST'])
def customer_unreport_loss():
    if request.method == 'POST':
        cardID = request.form.get('cardID')
        cardmima = request.form.get('cardmima')
        try:
            from mode12菜单版 import customer_cancel_loss_web as unreport_func
            result = unreport_func(cardID, cardmima)
            if result == '解挂成功':
                flash(result, 'success')
            else:
                flash(f'解挂失败：{result}', 'error')
            return redirect(url_for('customer_unreport_loss'))
        except Exception as e:
            flash(f'解挂失败：{e}', 'error')
    return render_template('customer_unreport_loss.html')

@app.route('/customer_change_pwd', methods=['GET', 'POST'])
def customer_change_pwd():
    if request.method == 'POST':
        cardID = request.form.get('cardID')
        old_pwd = request.form.get('old_pwd')
        new_pwd = request.form.get('new_pwd')
        confirm_pwd = request.form.get('confirm_pwd')
        try:
            from mode12菜单版 import customer_change_password_web as change_func
            result = change_func(cardID, old_pwd, new_pwd, confirm_pwd)
            if result == '密码修改成功':
                flash(result, 'success')
            else:
                flash(f'修改失败：{result}', 'error')
            return redirect(url_for('customer_change_pwd'))
        except Exception as e:
            flash(f'修改失败：{e}', 'error')
    return render_template('customer_change_pwd.html')

# 客户信息查询
@app.route('/customer_query', methods=['GET', 'POST'])
def customer_query():
    result = []
    if request.method == 'POST':
        accurate = {}
        fuzzy = {}
        range_query = {}
        if request.form.get('customerID'):
            accurate['customerID'] = request.form.get('customerID')
        if request.form.get('customerName'):
            fuzzy['customerName'] = request.form.get('customerName')
        if request.form.get('PID'):
            accurate['PID'] = request.form.get('PID')
        if request.form.get('PID_like'):
            fuzzy['PID'] = request.form.get('PID_like')
        if request.form.get('telephone'):
            accurate['telephone'] = request.form.get('telephone')
        if request.form.get('telephone_like'):
            fuzzy['telephone'] = request.form.get('telephone_like')
        if request.form.get('address'):
            fuzzy['address'] = request.form.get('address')
        from mode12菜单版 import query_userinfo
        result = query_userinfo(accurate, fuzzy, range_query)
    return render_template('customer_query.html', query_result=result)

# 银行卡信息查询
@app.route('/query_cardinfo', methods=['GET', 'POST'])
def query_cardinfo_route():
    result = []
    if request.method == 'POST':
        accurate = {}
        fuzzy = {}
        range_query = {}
        if request.form.get('cardID'):
            accurate['cardID'] = request.form.get('cardID')
        if request.form.get('cardID_like'):
            fuzzy['cardID'] = request.form.get('cardID_like')
        if request.form.get('curID'):
            accurate['curID'] = request.form.get('curID')
        if request.form.get('savingID'):
            accurate['savingID'] = request.form.get('savingID')
        if request.form.get('IsReportLoss'):
            accurate['IsReportLoss'] = request.form.get('IsReportLoss')
        if request.form.get('customerID'):
            accurate['customerID'] = request.form.get('customerID')
        if request.form.get('openDate_min') or request.form.get('openDate_max'):
            range_query['openDate'] = (request.form.get('openDate_min'), request.form.get('openDate_max'))
        if request.form.get('openMoney_min') or request.form.get('openMoney_max'):
            range_query['openMoney'] = (request.form.get('openMoney_min'), request.form.get('openMoney_max'))
        if request.form.get('balance_min') or request.form.get('balance_max'):
            range_query['balance'] = (request.form.get('balance_min'), request.form.get('balance_max'))
        result = query_cardinfo(accurate, fuzzy, range_query)
    return render_template('bankcard_manage.html', query_result=result)

# 存款业务查询
@app.route('/query_deposit', methods=['GET', 'POST'])
def query_deposit_route():
    result = []
    if request.method == 'POST':
        accurate = {}
        fuzzy = {}
        range_query = {}
        if request.form.get('savingID'):
            accurate['savingID'] = request.form.get('savingID')
        if request.form.get('savingName'):
            fuzzy['savingName'] = request.form.get('savingName')
        if request.form.get('descrip'):
            fuzzy['descrip'] = request.form.get('descrip')
        if request.form.get('cardID'):
            accurate['cardID'] = request.form.get('cardID')
        if request.form.get('cardID_like'):
            fuzzy['cardID'] = request.form.get('cardID_like')
        result = query_deposit(accurate, fuzzy, range_query)
    return render_template('deposit_manage.html', query_result=result)

@app.route('/bankcard_query', methods=['GET', 'POST'])
def bankcard_query():
    result = []
    if request.method == 'POST':
        accurate = {}
        fuzzy = {}
        range_query = {}
        if request.form.get('cardID'):
            accurate['cardID'] = request.form.get('cardID')
        if request.form.get('cardID_like'):
            fuzzy['cardID'] = request.form.get('cardID_like')
        if request.form.get('curID'):
            accurate['curID'] = request.form.get('curID')
        if request.form.get('savingID'):
            accurate['savingID'] = request.form.get('savingID')
        if request.form.get('IsReportLoss'):
            accurate['IsReportLoss'] = request.form.get('IsReportLoss')
        if request.form.get('customerID'):
            accurate['customerID'] = request.form.get('customerID')
        if request.form.get('openDate_min') or request.form.get('openDate_max'):
            range_query['openDate'] = (request.form.get('openDate_min'), request.form.get('openDate_max'))
        if request.form.get('openMoney_min') or request.form.get('openMoney_max'):
            range_query['openMoney'] = (request.form.get('openMoney_min'), request.form.get('openMoney_max'))
        if request.form.get('balance_min') or request.form.get('balance_max'):
            range_query['balance'] = (request.form.get('balance_min'), request.form.get('balance_max'))
        from mode12菜单版 import query_cardinfo
        result = query_cardinfo(accurate, fuzzy, range_query)
    return render_template('bankcard_query.html', query_result=result)

@app.route('/deposit_query', methods=['GET', 'POST'])
def deposit_query():
    result = []
    if request.method == 'POST':
        accurate = {}
        fuzzy = {}
        range_query = {}
        if request.form.get('savingID'):
            accurate['savingID'] = request.form.get('savingID')
        if request.form.get('savingName'):
            fuzzy['savingName'] = request.form.get('savingName')
        if request.form.get('descrip'):
            fuzzy['descrip'] = request.form.get('descrip')
        if request.form.get('cardID'):
            accurate['cardID'] = request.form.get('cardID')
        if request.form.get('cardID_like'):
            fuzzy['cardID'] = request.form.get('cardID_like')
        from mode12菜单版 import query_deposit
        result = query_deposit(accurate, fuzzy, range_query)
    return render_template('deposit_query.html', query_result=result)

@app.route('/transaction_pie')
def transaction_pie():
    # 查询所有交易记录
    transactions = view_all_transactions()
    # 统计各交易类型金额总和
    type_sum = defaultdict(float)
    for t in transactions:
        ttype = t.get('tradeType', '未知')
        try:
            money = float(t.get('tradeMoney', 0))
        except:
            money = 0
        type_sum[ttype] += money
    # 转为前端可用格式
    pie_data = [{'name': k, 'value': v} for k, v in type_sum.items()]
    return render_template('transaction_pie.html', pie_data=pie_data)

@app.route('/transaction_trend')
def transaction_trend():
    transactions = view_all_transactions()
    # 统计每日流水总额
    from collections import defaultdict
    from datetime import datetime
    day_sum = defaultdict(float)
    for t in transactions:
        date_str = t.get('tradeDate', '')
        try:
            # 只取日期部分
            day = date_str[:10]
            money = float(t.get('tradeMoney', 0))
        except:
            continue
        day_sum[day] += money
    # 按日期排序
    days = sorted(day_sum.keys())
    trend_data = {'dates': days, 'values': [day_sum[d] for d in days]}
    return render_template('transaction_trend.html', trend_data=trend_data)

if __name__ == '__main__':
    # 自动创建模板和静态目录
    os.makedirs('templates', exist_ok=True)
    os.makedirs('static', exist_ok=True)
    app.run(debug=True)